package databasetest.zx.com.databasetest.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;


import java.io.File;

/**
 * SQLite数据库管理类
 * <p>
 * 主要负责数据库资源的初始化,开启,关闭,以及获得DatabaseHelper帮助类操作
 *
 * @author shimiso
 */
public class DBManager {

    public final static int version = 1;
    private String databaseName;

    public static final String DB_KEY = "";//包数据库标识

    // 本地Context对象
    private Context mContext = null;

    private static DBManager dBManager = null;

    /**
     * 构造函数
     *
     * @param mContext
     */
    private DBManager(Context mContext) {
        super();
        this.mContext = mContext;

    }

    /***
     * 单态对象值为null
     **/

    public static void clearDbmanager() {
        dBManager = null;
    }

    public static DBManager getInstance(Context mContext, String databaseName) {
        dBManager = new DBManager(mContext);
        dBManager.databaseName = DB_KEY + databaseName;
        return dBManager;
    }

    /**
     * 关闭数据库 注意:当事务成功或者一次性操作完毕时候再关闭
     */
    public void closeDatabase(SQLiteDatabase dataBase, Cursor cursor) {
        if (null != dataBase) {
            dataBase.close();
        }
        if (null != cursor) {
            cursor.close();
        }
    }

    /**
     * 打开数据库
     */
    public SQLiteDatabase openDatabase() {
        return getDatabaseHelper().getWritableDatabase();
    }

    /**
     * 获取DataBaseHelper
     *
     * @return
     */
    public MyDataBaseHelper getDatabaseHelper() {
        return new MyDataBaseHelper(mContext, this.databaseName, null,
                version);
    }

    public int getVersion() {
        String path = getDatabasePath(databaseName).getPath();
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);
        return db.getVersion();
    }

    private File getDatabasePath(String name) {
        String EXTERN_PATH = "/data/data/" + mContext.getPackageName() + "/databases/";
        File f = new File(EXTERN_PATH);
        if (!f.exists()) {
            f.mkdirs();
        }
        return new File(EXTERN_PATH + name);
    }
}
